package com.scs.application.modules.base.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.base.entity.MatrHis;
import com.scs.application.modules.base.mapper.MatrHisMapper;
import com.scs.application.modules.base.service.MatrHisService;
import com.scs.application.modules.price.dto.AdjustBuildDTO;
import com.scs.application.modules.price.service.AdjustmentService;
import com.scs.application.modules.thirdparty.dto.his.HisChargeChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class MatrHisServiceImpl extends BaseServiceImpl<MatrHisMapper, MatrHis> implements MatrHisService {

    @Autowired
    private AdjustmentService adjustmentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeByHisChargeChange(HisChargeChange changeParam) {
        List<MatrHis> matrHisList = this.list(Wrappers.<MatrHis>query().eq("his_code",changeParam.getMatrCodeHis()));
        BusinessException.throwValidFailIf(ObjectUtil.length(matrHisList) > 1 ,"his编码找到多条物价信息,编码【%s】",changeParam.getMatrCodeHis());
        MatrHis matrHis = null;
        if (ObjectUtil.length(matrHisList) == 1) {
            matrHis = matrHisList.get(0);
        }
        if (matrHis == null) {
            matrHis = new MatrHis();
        }

        AdjustBuildDTO adjustBuild = new AdjustBuildDTO();
        adjustBuild.setHisCodeBefore(matrHis.getHisCode()).setHisPriceBefore(matrHis.getPricePatientAdult());

        matrHis.setHisCode(changeParam.getMatrCodeHis())
                .setName(changeParam.getMatrNameHis())
                .setHisCode(changeParam.getMatrCodeHis())
                .setFlagDisabled(changeParam.getIsDisabled() == 1? true :false)
                .setPricePatientAdult(changeParam.getPricePatientAdult())
                .setPricePatientChild(changeParam.getPricePatientChild())
                .setGmtModified(LocalDateTime.now());
        // 新增物价
        if (matrHis.isNewRecord()) {
            this.save(matrHis);
            return;
        }
        this.updateById(matrHis);

        // 生成调价单
        adjustBuild.setHisCodeAfter(matrHis.getHisCode()).setHisPriceAfter(matrHis.getPricePatientAdult());
        adjustmentService.buildByHisChange(Arrays.asList(adjustBuild), "his调价接口调用后创建", false);
    }
}
